package com.zhiwang.xiaoqu.ui

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.telephony.TelephonyManager
import android.text.TextUtils
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.zhiwang.xiaoqu.R
import com.zhiwang.xiaoqu.bus.LoginEvent
import com.zhiwang.xiaoqu.bus.WxLoginEvent
import com.zhiwang.xiaoqu.ktextension.setImmersive
import com.zhiwang.xiaoqu.mvp.model.Store
import com.zhiwang.xiaoqu.mvp.model.room.User
import com.zhiwang.xiaoqu.mvp.presenter.UserPresenter
import kotlinx.android.synthetic.main.activity_login.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import quickStartActivity
import suicideAfterTransition
import javax.inject.Inject

class LoginActivity : BaseActivity() {


    lateinit var wxApi: IWXAPI

    @Inject
    lateinit var userPresenter:UserPresenter

    companion object {
        fun start(context: AppCompatActivity) = context.quickStartActivity(LoginActivity::class.java)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.setImmersive(Color.TRANSPARENT, true)
        setContentView(R.layout.activity_login)

        wxApi = WXAPIFactory.createWXAPI(this, Store.WX_APP_ID)

        app_agreement.setOnClickListener {
            WebViewActivity.load(this, Store.URL_APP_AGREEMENT)
        }

        weixin_login.setOnClickListener {
            loginByWeixin()
        }
    }


    /**
     * 只能获得 access_token ，然后后台根据 access_token 请求 微信接口 获取 openid 后返回 token
     */
    private fun loginByWeixin() {
        val req = SendAuth.Req()
        req.scope = "snsapi_userinfo"
        req.state = "wechat_sdk_demo_test"
        wxApi.sendReq(req)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onWxLogin(e: WxLoginEvent) {
        userPresenter.checkWxBind(e.code, deviceId ?: "")
    }

    var deviceId: String? = null
    @SuppressLint("MissingPermission", "HardwareIds")
    fun getDeviceId() {

        deviceId = System.currentTimeMillis().toString()
        val telecomManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        deviceId = when {
            TextUtils.isEmpty(telecomManager.deviceId).not() -> telecomManager.deviceId
            Build.VERSION.SDK_INT > Build.VERSION_CODES.P -> Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> telecomManager.getImei(0)
            else -> ""
        }
//        deviceId?.apply { TokenManager.saveDevice(this) }
    }


     fun onLogin(user: User) {
        closeIme()
//        Toasty.message(R.string.login_success)
        EventBus.getDefault().post(LoginEvent())
        suicideAfterTransition()
//        Log.i(TAG, "onLogin: TTTTTTTT  ${user.token}")
    }

    fun closeIme() {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(window.decorView.windowToken, 0)
    }


}
